<?php

/**
 * OpenApi 接口控制器
 *
 * @author pufan
 */

namespace Portal\Controller;

use Think\Controller;
use Library\CardCode;
use Library\SMS;
use Library\User;
use Think\Log;

class OpenApiController extends Controller {
    function _initialize() {
        if (!IS_POST) { //禁止get访问
            exit;
        }
    }

    protected function api_return($errcode = 0, $errmsg = 'ok', $status = '', $data_name = '', $data = array()) {
        $json_data['errcode'] = $errcode;
        $json_data['errmsg'] = $errmsg;
        if ($errcode) {
            if ($data_name) {
                $json_data[$data_name] = $data;
            }
            \Think\Log::record('query_string: '.$_SERVER['QUERY_STRING'].' '.'api_return:'. $errcode.' openid: '.$_SESSION['open_id']);
            $this->ajaxReturn($json_data);
        }
        if ($data_name) {
            $json_data['data'] = array('status' => $status, $data_name => $data);
        } else {
            $json_data['data'] = array('status' => $status);
        }
        \Think\Log::record('query_string: '.$_SERVER['QUERY_STRING'].' args:'.json_encode($_POST).' '.'api_return:'. json_encode($json_data).' openid: '.$_SESSION['open_id']);
        $this->ajaxReturn($json_data);
    }

    /*
     * api 通用统计接口
     */
    public function tongji() {
        $objId = I('post.obj_id');
        switch ($objId) {
            case 1: //分享朋友圈
                break;
            case 2: //分享好友
                break;
            default:
                Log::record('tongji objId is Invalid');
        }
        $data['object_id'] = $objId;
        $data['userid'] = $_SESSION['user_id'];
        $data['openid'] = $_SESSION['open_id'];

        if ($_SESSION['devid']) {
            $data['devid'] = $_SESSION['devid'];
        }
        D('statistics')->add($data);
        $this->api_return(0, 'ok', 0);
    }

    /*
     * 卡券核销api接口
     */
    public function  cardVerification() {

        $cardId = I('post.card_id', '');
        $cardCode = I('post.card_num', '');
        $key = I('post.key', '');

        Log::record($cardId.$cardCode.$key);
        if (!$cardId || !$cardCode || !$key) {
            $this->api_return(0, 'ok', 1);
        }

        //验证码错误
        if(!sp_check_verify_code()){
            $this->api_return(0, 'ok', 5);
        }

        $card = CardCode::getInstance();
        $result = $card->checkConsume($cardId, $cardCode);

        //无效的卡券
        if (!$result) {
            $this->api_return(0, 'ok', 2);
        }

        $result = $card->checkConsumeKey($cardId, $key);

        //密码错误
        if (!$result) {
            $this->api_return(0, 'ok', 3);
        }

        $result = $card->consume($cardId, $cardCode);

        if ($result) {
            $this->api_return(0, 'ok', 0);
        } else {
            $this->api_return(0, 'ok', 4);
        }
    }

    /*
    * 发送手机验证码
    */
    function getPhoneCaptcha() {
        $sms = new SMS();
        $phone = I('post.phone_number', '', '/1[34578]{1}\d{9}$/');
        if (empty($phone)) {
            $this->api_return(0, 'ok', 1);
        }
        $nick = $_SESSION['wxuser']['nickname'] ? $_SESSION['wxuser']['nickname'] : '游客';
        $shark_openid = $_SESSION['open_id'];
        if (empty($nick) || empty($shark_openid)) {
            \Think\Log::record('getPhoneCaptcha nickname or open_id empty');
            $this->api_return(0, 'ok', 2);
        }

        $dx_count = S($_SESSION['open_id'].':dx_count');
        if ($dx_count >= C('PHONEVERIFY_COUNT_LIMIT')) {
            $this->api_return(0, 'ok', 4);  //每天限制发送3条短信
        }

        $rand_code = sprintf("%06d", mt_rand(0, 999999));

        $data['name'] = $nick;
        $data['code'] = $rand_code;
        $result = $sms->sendMsg('SMS_9690344', $phone, $data);

        if ($result != 0) {
            $this->api_return(0, 'ok', 3);
        }

        $sms_list = S('phone_verify:'.$shark_openid.':'.$phone);
        if ($sms_list) {
            $sms_list .= ','.$rand_code;
        } else {
            $sms_list = $rand_code;
        }

        S($_SESSION['open_id'].':dx_count', $dx_count+1, strtotime(date('Y-m-d',strtotime('+1 day'))) - time());

        S('phone_verify:'.$shark_openid.':'.$phone, $sms_list ,C('PHONEVERIFY_TIMEOUT'));
        $this->api_return(0, 'ok', 0);
    }

    /*
     * 验证码验证接口
     */
    function verifyPhoneCode() {
        $code = I('post.captcha_number', '');
        $phone = I('post.phone_number', '', '/1[34578]{1}\d{9}$/');
        if (!$code) {
            $this->api_return(0, 'ok', 1);
        }

        $shark_openid = $_SESSION['open_id'];
        $sms_list = S('phone_verify:'.$shark_openid.':'.$phone);

        if ($sms_list) {
            $code_list = explode(',', $sms_list);
        } else {
            $this->api_return(0, 'ok', 2); //不匹配
        }

        foreach ($code_list as $key => $value) {
            if ($value == $code) {
                $user = User::getInstance();
                if ($user->addPhone($phone)) {
                    $this->api_return(0, 'ok', 0); //验证通过
                } else {
                    $this->api_return(0, 'ok', 3); //验证失败
                }
            }
        }

        $this->api_return(0, 'ok', 2); //不匹配
    }
}

